package com.ytd.smartcanteen.weighting.dialog;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ytd.smartcanteen.weighting.MainActivity;
import com.ytd.smartcanteen.weighting.adapter.DishRecyclerAdapter;
import com.ytd.smartcanteen.weighting.adapter.ExpandableAdapter;
import com.ytd.smartcanteen.weighting.bean.MealCategoryInfo;
import com.ytd.smartcanteen.weighting.bean.MealInfo;
import com.ytd.smartcanteen.weighting.bean.MealTimeInfo;
import com.ytd.smartcanteen.weighting.util.FoodManager;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

import cn.ytd.smartcanteen.weighting.R;

public class SetDishDialog extends BaseDialog {
    List<MealTimeInfo> mData = new ArrayList<>();
    List<MealInfo> mList = new ArrayList<>();
    TextView btn_back;
    int cp = 0, gp = 0;
    private EditText mEvSearch;
    private ExpandableListView mEl;
    private TextView mTitle;
    private RecyclerView mRy;
    private ExpandableAdapter mExpandableAdapter;
    private DishRecyclerAdapter mRecyclerAdapter;
    private View mMenuView;

    public SetDishDialog(MainActivity context) {
        super(context);
        LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.pop_more, null);
        int h = context.getWindowManager().getDefaultDisplay().getHeight();
        //    btn_back  = (Button) mMenuView.findViewById(R.id.set_btn_back);
        mEvSearch = mMenuView.findViewById(R.id.ev_search);
        mEl = (ExpandableListView) mMenuView.findViewById(R.id.el);
        mTitle = (TextView) mMenuView.findViewById(R.id.title);
        mRy = (RecyclerView) mMenuView.findViewById(R.id.ry);
        btn_back = mMenuView.findViewById(R.id.set_btn_back);

        btn_back.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                //销毁弹出框
                dismiss();
            }
        });
        mEvSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                ChangeList();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mData = FoodManager.getInstance().getData();
        /**
         * 侧边栏餐品类表
         */
        mExpandableAdapter = new ExpandableAdapter(context, mData);
        mEl.setAdapter(mExpandableAdapter);
        mEl.setOnGroupClickListener((parent, view, groupPosition, id) -> {
            mTitle.setText(mData.get(groupPosition).mealTimeName);
            if (mExpandableAdapter != null) {
                mExpandableAdapter.setSelectPosition(groupPosition, 0);
            }
            gp = groupPosition;
            cp = 0;
            mRy.smoothScrollToPosition(0);
            changeListData(gp, 0);
            return false;
        });
        mEl.setOnChildClickListener((parent, view, groupPosition, childPosition, id) -> {
            if (mExpandableAdapter != null) {
                mExpandableAdapter.setSelectPosition(groupPosition, childPosition);
            }
            cp = childPosition;
            gp = groupPosition;
            mRy.smoothScrollToPosition(0);
            changeListData(groupPosition, childPosition);
            return true;
        });


        /**
         * 餐品列表
         */
        mRecyclerAdapter = new DishRecyclerAdapter(context);
        mRecyclerAdapter.setExpandableAdapter(mExpandableAdapter);
        mRy.setLayoutManager(new LinearLayoutManager(context));
        mRy.setAdapter(mRecyclerAdapter);
        try {
            initShow();
        } catch (Exception e) {

        }
        this.setContentView(mMenuView);
        this.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        this.setOutsideTouchable(false);
        this.setHeight(h - 50);
        this.setFocusable(true);
        this.setOutsideTouchable(false);
        this.setAnimationStyle(R.style.DialogShow);
        context.setTitle(context.getString(R.string.text_food_setting));
//        this.setOnDismissListener(() -> {
//            // 背景灰度回复
//            WindowManager.LayoutParams lp = context.getWindow().getAttributes();
//            lp.alpha = 1f;
//            context.getWindow().setAttributes(lp);
//        });
//

//        findViewById(R.id.click).setOnClickListener(v -> {
//            // 背景灰度设置
//            WindowManager.LayoutParams lp = getWindow().getAttributes();
//            lp.alpha = 0.5f;
//            getWindow().setAttributes(lp);
//            mPop.showAtLocation(this.getDecorView(), Gravity.BOTTOM, 0, 0);
//
//
//        });
    }

    private void changeListData(int groupPosition, int childPosition) {
        if (groupPosition >= mData.size() || childPosition >= mData.get(groupPosition).mMealCategoryInfos.size()) {
            return;
        }
        mTitle.setText(mData.get(groupPosition).mealTimeName);
        String mCategoryName = mData.get(groupPosition).mMealCategoryInfos.get(childPosition).id;
        mList.clear();
        if (mEvSearch.getText().toString().length() > 0) {
            mList.addAll(FoodManager.getInstance().searchFoodPageList(mCategoryName, mEvSearch.getText().toString()));
        } else {
            mList.addAll(mData.get(groupPosition).mMealCategoryInfos.get(childPosition).mMealInfos);
        }
        mRecyclerAdapter.setDataList(mList, mData.get(groupPosition).mealTimeId,
            mData.get(groupPosition).mMealCategoryInfos.get(childPosition).id);
    }


    public void Show(int gravity, int x, int y) {

        showAtLocation(mMenuView, gravity, x, y);
    }

    public void ChangeList() {
        String mCategoryId = mData.get(gp).mMealCategoryInfos.get(cp).id;
        mList.clear();
        if (mEvSearch.getText().toString().length() > 0) {
            mList.addAll(FoodManager.getInstance().searchFoodPageList(mCategoryId, mEvSearch.getText().toString()));
        } else {
            mList.addAll(mData.get(gp).mMealCategoryInfos.get(cp).mMealInfos);
        }

        mRecyclerAdapter.setDataList(mList, mData.get(gp).mealTimeId,
            mData.get(gp).mMealCategoryInfos.get(cp).id);
        mData = FoodManager.getInstance().getData();
        mExpandableAdapter.setDataList(mData);
    }

    void initShow() {
        int initGroup = getInitGroup();
        mEl.expandGroup(initGroup);
        int initChild = getInitChild();
        if (mExpandableAdapter != null) {
            mExpandableAdapter.setSelectPosition(initGroup, initChild);
        }
        mTitle.setText(mData.get(initGroup).mealTimeName);
        mList.clear();
        mList.addAll(mData.get(initGroup).mMealCategoryInfos.get(initChild).mMealInfos);
        mRecyclerAdapter.setDataList(mList, mData.get(initGroup).mealTimeId,
            mData.get(initGroup).mMealCategoryInfos.get(initChild).id);
        int foodPosition = getInitFoodPosition();
        mRy.smoothScrollToPosition(foodPosition);
    }

    private int getInitFoodPosition() {
        MealInfo currentMealInfo = FoodManager.getInstance().getCurrentMealInfo();
        for (MealInfo mealInfo : mList) {
            if (currentMealInfo.foodId.equals(mealInfo.foodId)) {
                return mList.indexOf(mealInfo);
            }
        }
        return 0;
    }

    private int getInitChild() {
        MealInfo currentMealInfo = FoodManager.getInstance().getCurrentMealInfo();
        if (currentMealInfo != null && mData.size() > 0 && mData.get(0).mMealCategoryInfos != null) {
            for (MealCategoryInfo mealCategoryInfo : mData.get(0).mMealCategoryInfos) {
                if (currentMealInfo.foodCategoryId.equals(mealCategoryInfo.id)) {
                    return mData.get(0).mMealCategoryInfos.indexOf(mealCategoryInfo);
                }
            }
        }
        return 0;
    }

    private int getInitGroup() {
        MealInfo currentMealInfo = FoodManager.getInstance().getCurrentMealInfo();
        if (currentMealInfo != null) {
            for (MealTimeInfo datum : mData) {
                if (datum.mealTimeId.equals(currentMealInfo.mealTimeId)) {
                    return mData.indexOf(datum);
                }
            }
        }
        return 0;
    }

    public void updateFoodCategory(@Nullable MealCategoryInfo updateFoodCategory) {
        if (updateFoodCategory == null || mData == null) {
            return;
        }
        for (MealTimeInfo datum : mData) {
            for (MealCategoryInfo mealCategoryInfo : datum.mMealCategoryInfos) {
                if (mealCategoryInfo.id.equals(updateFoodCategory.id)) {
                    mealCategoryInfo.categoryName = updateFoodCategory.categoryName;
                    break;
                }
            }
        }
        if (mExpandableAdapter != null) {
            mExpandableAdapter.notifyDataSetChanged();
        }
    }

    public void updateBindFood() {
        if (mRecyclerAdapter != null) {
            mRecyclerAdapter.notifyDataSetChanged();
        }
        if (mExpandableAdapter != null) {
            mExpandableAdapter.notifyDataSetChanged();
        }
    }

    public void updateFood(@Nullable MealInfo updateFood) {
        if (mRecyclerAdapter == null || mList == null) {
            return;
        }
        if (updateFood == null) {
            mData = FoodManager.getInstance().getData();
            ChangeList();
            updateBindFood();
            return;
        }
        if (mEvSearch.getText().toString().length() > 0) {
            mList.clear();
            mList.addAll(FoodManager.getInstance().searchFoodPageList("", mEvSearch.getText().toString()));
            mRecyclerAdapter.notifyDataSetChanged();
            return;
        }
        if (mList.size() > 0) {
            String categoryId = mList.get(0).foodCategoryId;
            if (!categoryId.equals(updateFood.foodCategoryId)) {
                return;
            }
        }
        boolean isChange = false;
        for (MealInfo mealInfo : mList) {
            if (mealInfo.foodId.equals(updateFood.foodId)) {
                mealInfo.foodCategoryId = updateFood.foodCategoryId;
                mealInfo.clipWeight = updateFood.clipWeight;
                mealInfo.foodName = updateFood.foodName;
                mealInfo.foodLogo = updateFood.foodLogo;
                mealInfo.price = String.valueOf(updateFood.price);
                mealInfo.priceUnit = updateFood.priceUnit;
                mealInfo.remark = updateFood.remark;
                mealInfo.weight = updateFood.weight;
                mealInfo.weightUnit = updateFood.weightUnit;
                isChange = true;
                break;
            }
        }
        if (!isChange) {
            mList.add(updateFood);
        }
        mRecyclerAdapter.notifyDataSetChanged();
    }

    public void updateMealTime() {
        int groupCount = mExpandableAdapter.getGroupCount();
        for (int i = 0; i < groupCount; i++) {
            mEl.collapseGroup(i);
        }
        mData = FoodManager.getInstance().getData();
        if (mExpandableAdapter != null) {
            mExpandableAdapter.setDataList(mData);
        }
        initShow();
    }
}